use std::net::TcpListener;
use log::{error, debug, info};
use crate::utils::Error;

// static IP: &str = "10.122.202.179";
static IP: &str = "127.0.0.1";
static PORT: u16 = 8899;

mod smtp;
mod http;
mod utils;

use simplelog::*;
use std::fs::File;

fn main() {
    //初始化日志库
    // simple_logger::init_with_level(log::Level::Debug).unwrap();
    CombinedLogger::init(
        vec![
            TermLogger::new(LevelFilter::Info, Config::default(), TerminalMode::Mixed, ColorChoice::Auto),
            WriteLogger::new(LevelFilter::Debug, Config::default(), File::create("my_rust_binary.log").unwrap()),
        ]
    ).unwrap();

    let listener = TcpListener::bind((IP, PORT)).unwrap();
    info!("Server Started");
    info!("IP:{}\tPORT:{}",IP,PORT);
    //循环监听8899号端口
    for stream in listener.incoming() {
        let client_socket = match stream {
            Ok(socket) => {
                info!("Connection Established! Client IP address:{}",socket.peer_addr().unwrap().ip());
                socket
            }
            Err(_) => {
                error!("Connection Established Failed!");
                continue;
            }
        };
        //进入http handler 处理http请求
        match http::handlers::http_handler(client_socket) {
            Ok(_) => { info!("Handle Connection Succeed.") }
            //根据错误信息记录日志
            Err(e) => {
                match e {
                    Error::SmtpError(_) => { error!("Smtp Error") }
                    Error::HttpError(_) => { error!("Http Error") }
                    Error::InternalError => { error!("Handle Error!Something went wrong in system...") }
                    Error::ConnectionError(_) => { error!("Connection Error.") }
                }
            }
        }
    }
}
